package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.omg.PortableInterceptor.SUCCESSFUL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import ysq.xyg.model.BaseDepart;
import ysq.xyg.model.BaseDepartMenu;
import ysq.xyg.model.BaseMenu;
import ysq.xyg.model.info.BaseDepartInfo;
import ysq.xyg.model.info.Page;
import ysq.xyg.model.info.ReturnInfo;
import ysq.xyg.service.BaseDepartMenuService;
import ysq.xyg.service.BaseDepartService;
import ysq.xyg.service.BaseMenuService;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;
import ysq.xyg.util.DateUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yu sheng qiang
 * @create 2017-04-19 14:15
 **/
@Controller
@RequestMapping("/baseDepart")
public class BaseDepartController extends BaseController {
    private static Logger log= LoggerFactory.getLogger(BaseDepartController.class);
    @Resource
    private BaseDepartService baseDepartService;
    @Resource
    private BaseMenuService baseMenuService;
    @Resource
    private BaseDepartMenuService baseDepartMenuService;
    private BaseDepart baseDepart;

    @RequestMapping("/listPage")
    public ModelAndView List(HttpServletRequest request, HttpServletResponse response,String menuid){
        return new ModelAndView("/baseDepartList").addObject("headTitle",acceptTitle(menuid,baseMenuService));
    }

    @RequestMapping(value = "/JsonList",method = RequestMethod.POST)
    public @ResponseBody JSONObject JsonList(BaseDepart baseDepart,Page page) throws MalformedURLException, UnsupportedEncodingException {
        baseDepart.setRemovetag(BaseConstant.REMOVE_N);
        PageInfo<BaseDepart> pageInfo=baseDepartService.pageInfo(baseDepart,page.getLimit(),page.getPage());
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","");
        jsonObject.put("count",pageInfo.getTotal());
        if(pageInfo !=null && pageInfo.getList() !=null && pageInfo.getList().size() > 0){
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for(BaseDepart item:pageInfo.getList()){
                row=new JSONObject();
                row.put("departid",item.getDepartid());
                row.put("departname",item.getDepartname());
                row.put("createtime", DateUtil.DateToStr(item.getCreatetime(),DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/SelectEntity",method = RequestMethod.GET)
    public ModelAndView SelectEntity(String departId){
        ModelAndView view=new ModelAndView("/baseDepartUpdateOrSave");
        List<BaseDepartMenu> baseDepartMenuList=null;
        if (departId != null && !"".equals(departId)){
            BaseDepart baseDepart=(BaseDepart)baseDepartService.selectByPrimaryKey(departId);
            //菜单权限
            BaseDepartMenu baseDepartMenu=new BaseDepartMenu();
            baseDepartMenu.setDepartid(baseDepart.getDepartid());
            baseDepartMenu.setRemovetag(BaseConstant.REMOVE_N);
            baseDepartMenuList=baseDepartMenuService.select(baseDepartMenu);
            view.addObject(baseDepart);
        }
        //菜单查询
        BaseMenu baseMenu=new BaseMenu();
        baseMenu.setRemovetag(BaseConstant.REMOVE_N);
        List<BaseMenu> baseMenusList=baseMenuService.select(baseMenu);
        List<BaseMenu> baseMenusListOne=new ArrayList<BaseMenu>();
        if(baseMenusList!=null && baseMenusList.size() > 0){
            for(BaseMenu baseMenu1:baseMenusList){
                if(BaseConstant.MENU_ONE.equals(baseMenu1.getMenugrade())){
                    List<BaseMenu> baseMenusListTwo=new ArrayList<BaseMenu>();
                    for(BaseMenu baseMenu2:baseMenusList){
                        if(baseMenu1.getMenuid().equals(baseMenu2.getParentmenuid())){
                            baseMenu2.setCheck(isCheck(baseDepartMenuList,baseMenu2.getMenuid()));
                            baseMenusListTwo.add(baseMenu2);
                        }
                    }
                    baseMenu1.setChildList(baseMenusListTwo);
                    baseMenu1.setCheck(isCheck(baseDepartMenuList,baseMenu1.getMenuid()));
                    baseMenusListOne.add(baseMenu1);
                }
            }
        }
        view.addObject("baseMenusListOne",baseMenusListOne);
        return view;
    }

    @RequestMapping(value = "/UpdateOrAddEntity",method = RequestMethod.POST)
    public @ResponseBody JSONObject UpdateOrAddEntity(BaseDepartInfo baseDepartInfo){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(baseDepartInfo.getDepartid()==null || "".equals(baseDepartInfo.getDepartid())){
            baseDepart=new BaseDepart();
            baseDepart.setDepartid(BaseUtil.uId());
            int le=baseDepart.getDepartid().length();
            baseDepart.setCreatetime(new Date());
            baseDepart.setRemovetag(BaseConstant.REMOVE_N);
            baseDepart.setDepartname(baseDepartInfo.getDepartName());
            int id=baseDepartService.insert(baseDepart);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_INSERT);
            }else if(StringUtil.isNotEmpty(baseDepartInfo.getMenuIdList())){
                SetContent(baseDepartInfo.getDepartid(),baseDepartInfo.getMenuIdList());
            }
        }else{
            baseDepart=baseDepartService.selectByPrimaryKey(baseDepartInfo.getDepartid());
            baseDepart.setDepartname(baseDepartInfo.getDepartName());
            baseDepart.setCreatetime(new Date());
            int id=baseDepartService.updateByPrimaryKey(baseDepart);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_UPDATE);
            }else if(StringUtil.isNotEmpty(baseDepartInfo.getMenuIdList())){
                SetContent(baseDepartInfo.getDepartid(),baseDepartInfo.getMenuIdList());
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    @RequestMapping(value = "/DeleteEntity",method = RequestMethod.GET)
    public @ResponseBody JSONObject DeleteEntity(String departId){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(departId)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            BaseDepart baseDepart=baseDepartService.selectByPrimaryKey(departId);
            if(baseDepart == null){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_BUCHUNZAI);
            }else{
                baseDepart.setRemovetag(BaseConstant.REMOVE_Y);
                int id=baseDepartService.updateByPrimaryKey(baseDepart);
                if(id <= 0){
                    returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_DELETE);
                }
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/listEntity",method = RequestMethod.GET)
    @ResponseBody
    public List<BaseDepart> listEntity(){
        BaseDepart baseDepart=new BaseDepart();
        baseDepart.setRemovetag(BaseConstant.REMOVE_N);
        return baseDepartService.select(baseDepart);
    }
    protected boolean isCheck(List<BaseDepartMenu> list,String menuId){
        boolean falge=false;
        if(list != null && list.size() > 0){
            for (BaseDepartMenu bMenu:list) {
                if(menuId.equals(bMenu.getMenuid())){
                    falge=true;
                    break;
                }
            }
        }
        return falge;
    }
    protected void  SetContent(String departId,String menuIds){
        //设置权限
        BaseDepartMenu baseDepartMenu=new BaseDepartMenu();
        baseDepartMenu.setDepartid(departId);
        baseDepartMenu.setRemovetag(BaseConstant.REMOVE_N);
        List<BaseDepartMenu> baseDepartMenuList=baseDepartMenuService.select(baseDepartMenu);
        //添加
        String[] menuIdList=menuIds.split(",");
        for (String menuId:menuIdList){
            boolean falge=true;
            if(baseDepartMenuList!=null && baseDepartMenuList.size() > 0){
                for (BaseDepartMenu bMenu:baseDepartMenuList){
                    if(bMenu.getMenuid().equals(menuId)){
                        falge=false;
                    }
                }
            }
            if(falge){
                //存储权限
                BaseDepartMenu bdMenu=new BaseDepartMenu();
                bdMenu.setDepartmenuid(BaseUtil.uId());
                bdMenu.setDepartid(departId);
                bdMenu.setCreatetime(new Date());
                bdMenu.setMenuid(menuId);
                bdMenu.setRemovetag(BaseConstant.REMOVE_N);
                baseDepartMenuService.insert(bdMenu);
            }
        }
        //删除操作
        for (BaseDepartMenu bMenu:baseDepartMenuList){
            boolean isDelete=true;
            for (String menuId:menuIdList){
                if(menuId.equals(bMenu.getMenuid())){
                    isDelete=false;
                }
            }
            if(isDelete){
                baseDepartMenuService.delete(bMenu);
            }
        }
    }
}
